﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SYT.Common.QuartzUtil
{
    public class QuartzHelper
    {
        private static IScheduler _scheduler;
        private static IJobDetail _jobDetail;
        private static ITrigger _trigger;

        static QuartzHelper()
        {
            var t=InitScheduler();
        }

        public static async Task InitScheduler()
        {
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            _scheduler = await schedFact.GetScheduler();
        }

        public static void Run()
        {
            _scheduler.Start();
        }


        public static void Stop()
        {
            //判断调度是否已经关闭
            if (!_scheduler.IsShutdown)
            {
                //等待任务运行完成
                _scheduler.Shutdown(true);
            }
        }

        /// <summary>
        /// 创建Job任务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jobName"></param>
        /// <param name="jobGroup"></param>
        /// <param name="triggerName"></param>
        /// <param name="cronExpression"></param>
        public static void CreateTaskJob<T>(string jobName, string jobGroup, string triggerName, string cronExpression, IDictionary<string, object> jobData = null) where T : IJob
        {
            if (jobData == null)
                jobData = new Dictionary<string, object>();
            _jobDetail = JobBuilder.Create<T>()
                    .WithIdentity(jobName, jobGroup)
                    .SetJobData(new JobDataMap(jobData))
                    .Build();

            _trigger = TriggerBuilder.Create()
              .WithIdentity(triggerName, jobGroup)
              .WithCronSchedule(cronExpression)
              .Build();

            _scheduler.ScheduleJob(_jobDetail, _trigger);

        }
    }
}
